<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\common\service;

/**
 * 系统服务基础类
 * JWT https://github.com/QThans/jwt-auth
 */

use thans\jwt\facade\JWTAuth;

class BaseService
{
    /**
     * 获取当前登录用户id
     * @return mixed
     */
    public static function getLoginUserId(): mixed
    {
        try {
            $payload = JWTAuth::auth();
            return $payload['userId']->getValue();
        } catch (\Exception $e) {
            abort(420, $e->getMessage());
        }
    }

    /**
     * 获取当前登录用户id,获取不到id返回空数据不抛出异常
     * @return mixed
     */
    public static function getLoginUserIdNoAuth(): mixed
    {
        try {
            $payload = JWTAuth::auth();
            return $payload['userId']->getValue();
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 生成token
     * @param $data
     * @return string
     */
    public static function buildToken($data): string
    {
        return JWTAuth::builder($data);
    }

    /**
     * 刷新token
     * @return string
     */
    public static function refreshToken()
    {
        return JWTAuth::refresh();
    }

    /**
     * 生成随机字符串
     * @param $length
     * @return string
     */
    public static function randomStr($length = 32)
    {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        $str = '';

        for ($i = 0; $i < $length; $i++) {
            $index = rand(0, strlen($chars) - 1);
            $str .= $chars[$index];
        }

        return $str;
    }
}